package com.yutian.example.demo.common.vo;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.yutian.example.demo.common.exceptions.MyParamException;
import com.yutian.example.demo.common.utils.AssertParamUtil;
import com.yutian.example.demo.common.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.List;
import java.util.stream.Collectors;

public abstract class PageBaseRequest extends BaseRequest {

    /**
     * 第几页
     * 注：从1开始
     */
    private Integer pageNumber;

    /**
     * 每页数目
     */
    private Integer pageSize;

    /**
     * 格式：+id,-name
     */
    private String sorts;

    @Override
    public void check() throws MyParamException {
        AssertParamUtil.isTrue(pageNumber >= 1, "page.size.less.than.min", new String[]{"1"});
        AssertParamUtil.isTrue(pageSize >= 1, "page.size.less.than.min", new String[]{"1"});
    }

    private Sort toSort() {
        Sort sortObj = null;
        if(StringUtils.isBlank(sorts)){
            sortObj = Sort.unsorted();
        } else {
            List<Sort.Order> orders = Lists.newArrayList();
            Splitter.on(",").omitEmptyStrings().split(sorts).forEach(col -> {
                if(!col.startsWith("+") && !col.startsWith("-")){
                    orders.add(Sort.Order.asc(StringUtil.toLowerUnderScore(col)));
                } else if(col.startsWith("+")) {
                    orders.add(Sort.Order.asc(StringUtil.toLowerUnderScore(col.substring(1))));
                } else if(col.startsWith("-")) {
                    orders.add(Sort.Order.desc(StringUtil.toLowerUnderScore(col.substring(1))));
                }
            });
            sortObj = Sort.by(orders);
        }
        return sortObj;
    }

    public Integer getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(Integer pageNumber) {
        this.pageNumber = pageNumber;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public String getSorts() {
        return sorts;
    }

    public void setSorts(String sorts) {
        this.sorts = sorts;
    }

    public PageRequest getPage() {
        return PageRequest.of(pageNumber - 1, pageSize, getSort());
    }

    public Sort getSort() {
        return toSort();
    }

    public String getSortSql() {
        Sort sort = getSort();
        if(sort.isUnsorted()){
            return null;
        }
        return sort.stream().map(it -> {
            return it.getProperty() + " " + it.getDirection().name();
        }).collect(Collectors.joining(","));
    }

    public Long getOffset() {
        return getPage().getOffset();
    }
}
